import {
  createContext,
  useContext,
  useState,
  ReactNode,
  useEffect,
} from "react";

import {
  getUserInfo,
  regAndLogin,
  User,
  logoutSys,
  LoginApp,
} from "@/api/User";
import { setToken, removeToken } from "@/utils/Token";

export interface logReg {
  token: string;
  add: boolean;
}

// 用户上下文类型
interface UserContextType {
  user: User | null;
  isAuthenticated: boolean;
  login: (
    phoneNumber: string,
    kaptchaKey: string,
    kaptchaValue: string
  ) => Promise<logReg>;
  loginByUserName: (
    usernamem: string,
    password: string,
    uuid: string,
    code: string
  ) => Promise<logReg>;
  logout: () => void;
  updateProfile: (profile: Partial<User>) => void;
}

const UserContext = createContext<UserContextType | undefined>(undefined);

// 默认头像列表
export const DEFAULT_AVATARS = [
  "/api/placeholder/80/80?text=👨‍💼",
  "/api/placeholder/80/80?text=👩‍💼",
  "/api/placeholder/80/80?text=👨‍💻",
  "/api/placeholder/80/80?text=👩‍💻",
  "/api/placeholder/80/80?text=👨‍🎨",
  "/api/placeholder/80/80?text=👩‍🎨",
  "/api/placeholder/80/80?text=👨‍🔬",
  "/api/placeholder/80/80?text=👩‍🔬",
  "/api/placeholder/80/80?text=👨‍🏫",
  "/api/placeholder/80/80?text=👩‍🏫",
];

export const UserProvider = ({ children }: { children: ReactNode }) => {
  const [user, setUser] = useState<User | null>(null);

  const login = async (
    phoneNumber: string,
    kaptchaKey: string,
    kaptchaValue: string
  ): Promise<logReg> => {
    // 模拟登录逻辑 - 检查是否是新用户
    const loginData = await regAndLogin({
      phoneNumber,
      kaptchaKey,
      kaptchaValue,
    });
    const { data } = loginData;
    const { token, add } = data;
    if (token?.length > 0) {
      setToken(token);
      getAjaxUser();
    }
    return {
      token,
      add,
    };

    // const isNewUser = !localStorage.getItem(`user_${phone}`);

    // if (isNewUser) {
    //   // 新用户注册
    //   const newUser: User = {
    //     id: Date.now().toString(),
    //     phone,
    //     credits: 100, // 新用户赠送100积分
    //     isProfileComplete: false,
    //   };
    //   localStorage.setItem(`user_${phone}`, JSON.stringify(newUser));
    //   setUser(newUser);
    // } else {
    //   // 老用户登录
    //   const savedUser = JSON.parse(
    //     localStorage.getItem(`user_${phone}`) || "{}"
    //   );
    //   setUser(savedUser);
    // }
  };

  const loginByUserName = async (
    username: string,
    password: string,
    uuid: string,
    code: string
  ): Promise<logReg> => {
    // 模拟登录逻辑 - 检查是否是新用户
    const loginData = await LoginApp({
      username,
      password,
      uuid,
      code,
    });

    const token = loginData?.data?.token;
    console.info("loginData", loginData);
    if (token?.length > 0) {
      setToken(token);
      getAjaxUser();
    }
    return {
      token,
      add: false,
    };
  };

  const getAjaxUser = async () => {
    const loginUser = await getUserInfo();
    if (loginUser?.user) {
      setUser(loginUser.user);
    }
  };

  const logout = async () => {
    await logoutSys();
    removeToken();
    setUser(null);
  };

  const updateProfile = (profile: Partial<User>) => {
    if (user) {
      const updatedUser = { ...user, ...profile };
      setUser(updatedUser);
      // localStorage.setItem(`user_${user.phone}`, JSON.stringify(updatedUser));
    }
  };

  useEffect(() => {
    getAjaxUser();
  }, []);

  return (
    <UserContext.Provider
      value={{
        user,
        isAuthenticated: !!user,
        login,
        loginByUserName,
        logout,
        updateProfile,
      }}
    >
      {children}
    </UserContext.Provider>
  );
};

export const useUser = () => {
  const context = useContext(UserContext);
  if (context === undefined) {
    throw new Error("useUser must be used within a UserProvider");
  }
  return context;
};
